<?php
namespace app\common;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtHelper
{
    public static function createToken($payload)
    {
        $key = config('jwt_secret_key');
        $expire = config('jwt_expire');
        $issuedAt = time();

        $payload = array_merge([
                                   'iat' => $issuedAt,
                                   'exp' => $issuedAt + $expire,
                               ], $payload);

        return JWT::encode($payload, $key, 'HS256');
    }

    public static function verifyToken($token)
    {
        $key = config('jwt_secret_key');
        try {
            $decoded = JWT::decode($token, new Key($key, 'HS256'));
            return (array) $decoded;
        } catch (\Exception $e) {
            return null;
        }
    }

    public static function shouldRefreshToken($payload)
    {
        if (!isset($payload['exp']) || !isset($payload['iat'])) {
            return false;
        }

        $exp = (int)$payload['exp'];
        $now = time();
        $refreshTtl = config('jwt_refresh_ttl');

        return ($exp - $now) < $refreshTtl;
    }
}
